# chat/serializers.py
from rest_framework import serializers
from django.utils import timezone
from django.db.models import Q
from .models import Conversation, Message, ConversationParticipant, UserStatus
from accounts.models import Student, Teacher
from accounts.jwt_utils import decode_jwt_token

class StudentSerializer(serializers.ModelSerializer):
    """学生序列化器"""

    class Meta:
        model = Student
        fields = ['student_id', 'name', 'grade', 'major', 'school']


class TeacherSerializer(serializers.ModelSerializer):
    """教师序列化器"""

    class Meta:
        model = Teacher
        fields = ['teacher_id', 'name', 'title', 'department', 'school']


class UserStatusSerializer(serializers.ModelSerializer):
    """用户状态序列化器"""
    student = StudentSerializer(required=False)
    teacher = TeacherSerializer(required=False)

    class Meta:
        model = UserStatus
        fields = ['student', 'teacher', 'user_type', 'is_online', 'last_seen']


class MessageSerializer(serializers.ModelSerializer):
    """消息序列化器"""
    sender = serializers.SerializerMethodField()
    is_mine = serializers.SerializerMethodField()

    class Meta:
        model = Message
        fields = ['id', 'sender', 'content', 'is_read', 'is_mine', 'created_at']

    def get_sender(self, obj):
        if obj.sender_student:
            return {
                'id': obj.sender_student.student_id,
                'name': obj.sender_student.name,
                'type': 'student'
            }
        else:
            return {
                'id': obj.sender_teacher.teacher_id,
                'name': obj.sender_teacher.name,
                'type': 'teacher'
            }

    def get_is_mine(self, obj):
        request = self.context.get('request')
        if not request or not hasattr(request.user, 'student') and not hasattr(request.user, 'teacher'):
            return False

        if hasattr(request.user, 'student') and obj.sender_student == request.user.student:
            return True
        if hasattr(request.user, 'teacher') and obj.sender_teacher == request.user.teacher:
            return True
        return False


class ConversationSerializer(serializers.ModelSerializer):
    """会话序列化器"""
    participants = serializers.SerializerMethodField()
    last_message = serializers.SerializerMethodField()
    unread_messages = serializers.SerializerMethodField()

    class Meta:
        model = Conversation
        fields = ['id', 'participants', 'created_at', 'updated_at', 'last_message', 'unread_messages']

    import jwt
    from django.conf import settings
    from accounts.models import Student, Teacher
    from accounts.jwt_utils import decode_jwt_token  # 假设已有JWT解码工具

    def get_participants(self, obj):
        """通过Token识别用户，获取会话参与者信息（排除当前用户）"""
        request = self.context.get('request')
        if not request:
            return None

        # 从请求头中获取Token
        auth_header = request.headers.get('Authorization', '')
        if not auth_header.startswith('Bearer '):
            return None  # 未提供有效Token，无法识别用户

        token = auth_header.split(' ')[1]
        try:
            # 解码Token获取用户信息
            payload = decode_jwt_token(token)
            if not payload:
                return None

            user_id = payload['user_id']
            user_type = payload['user_type']  # 'student'或'teacher'
            print(user_id, user_type)
        except Exception as e:
            print(f"Token解码失败: {e}")
            return None

        # 根据Token中的用户信息获取当前用户对象
        try:
            if user_type == 'student':
                current_user = Student.objects.get(id=user_id)
                current_user_type = 'student'
            elif user_type == 'teacher':
                current_user = Teacher.objects.get(id=user_id)
                current_user_type = 'teacher'
            else:
                return None  # 无效的用户类型
        except Exception as e:
            print(f"用户获取失败: {e}")
            return None

        other_participants = []
        # 遍历会话参与者
        for participant in obj.conversationparticipant_set.all():
            print(f"participant.student:{participant.student}")
            print(f"participant.teacher:{participant.teacher}")
            # 跳过当前用户
            if (current_user_type == 'student' and participant.student == current_user) or \
                    (current_user_type == 'teacher' and participant.teacher == current_user):
                continue

            # 序列化参与者用户信息
            if participant.user_type == 'student':
                serializer = StudentSerializer(participant.student)
                user_data = serializer.data
                user_data['type'] = 'student'
            else:
                serializer = TeacherSerializer(participant.teacher)
                user_data = serializer.data
                user_data['type'] = 'teacher'

            # 获取在线状态
            try:
                status_qs = Q(student=participant.student,
                              user_type='student') if participant.user_type == 'student' else \
                    Q(teacher=participant.teacher, user_type='teacher')
                status = UserStatus.objects.get(status_qs)
                user_data['is_online'] = status.is_online
                user_data['last_seen'] = status.last_seen
            except UserStatus.DoesNotExist:
                user_data['is_online'] = False
                user_data['last_seen'] = None

            other_participants.append(user_data)

        return other_participants

    def get_last_message(self, obj):
        last_message = obj.messages.last()
        if last_message:
            serializer = MessageSerializer(last_message, context=self.context)
            return serializer.data
        return None

    def get_unread_messages(self, obj):
        request = self.context.get('request')
        if not request or not hasattr(request.user, 'student') and not hasattr(request.user, 'teacher'):
            return 0

        # 获取当前用户
        if hasattr(request.user, 'student'):
            current_user = request.user.student
            current_user_type = 'student'
        else:
            current_user = request.user.teacher
            current_user_type = 'teacher'

        # 获取参与者
        try:
            participant = obj.conversationparticipant_set.get(
                Q(student=current_user, user_type='student') if current_user_type == 'student' else
                Q(teacher=current_user, user_type='teacher')
            )
            return participant.unread_messages
        except ConversationParticipant.DoesNotExist:
            return 0